import { SimulateController } from "../Controller";
import { TimeSeryService } from "./subs/TimeSeryService";
import { TimeLineService } from "./subs/TimeLineService";
import { RouterName } from "@/views/router";
import { SubWinName } from "../types/Win";
import { ChartSubType, TimeSeryMountedStorageData, UrlParam } from "../types/charts";
import { ChartOpenParam } from "../types/Socket";
import { storage } from '@/util/common';
import { StorageKey } from "../types/Controller";
import { SimulateStatusType } from "../_";

export class ChartsService {

  controller: SimulateController;
  timeSeryService: TimeSeryService;
  timeLineService: TimeLineService;
  simStartTime = null
  simClockRatio = 1
  simStepSize = 1000
  instanceId = ''
  simStatus = SimulateStatusType.initing

  wparam = {} as UrlParam

  constructor(c: SimulateController) {
    this.controller = c;
    this.timeSeryService = new TimeSeryService(this);
    this.timeLineService = new TimeLineService(this);
  }

  serviceInit() {
    this.simStartTime = null;
    this.simClockRatio = 1;
    this.simStepSize = 1000;
    this.timeSeryService.serviceInit();
  }

  async init() {
    const params = this.wparam = this.controller.winService.getQueryParams() as UrlParam;
    this.instanceId = params.instanceId || '';
    console.log(params, 'url params');
    switch (params.type) {
      case ChartSubType.TimeSery: // 时间序列图
        this.timeSeryService.init(params);
        break;
      case ChartSubType.TimeLine:
        await this.timeLineService.init(params);
        break;
      default:
    }
  }

  openChartWin(p: ChartOpenParam) {
    let urlParam = {
      ...p,
      type: ChartSubType.TimeSery,
    } as UrlParam;
    if (p.uiId) {
      urlParam = {
        ...urlParam,
        projectId: this.controller.projectId,
        modelId: this.controller.modelId,
        simulationSessionId: this.controller.sessionId,
        stepSize: this.controller.chartsService.simStepSize.toString()
      };
    }
    this.controller.winService.openPluginSubWin(
      RouterName.Charts,
      { width: 800, height: 500, skipTaskbar: false, title: SubWinName.Charts },
      urlParam
    );
  }

  openChartWinDirectly(instanceId: string, title: string, cb: (data: TimeSeryMountedStorageData) => void) {
    storage.set(StorageKey.IsTimeSeryMounted, { isMounted: false });
    this.openChartWin({
      instanceId: instanceId,
      title: title,
    });
    let isMountedTimer = window.setInterval(() => {
      const timeSeryMountedData = storage.get(StorageKey.IsTimeSeryMounted);
      if (timeSeryMountedData && timeSeryMountedData.isMounted) {
        clearInterval(isMountedTimer);
        cb(timeSeryMountedData);
      }
    }, 300);
  }
}
